<?php

namespace app\customer\logic;
use app\common\library\RedissLock;
use app\common\service\CommonSystemImportService;
use app\data\util\HttpUtil;
use think\facade\Db;
use app\api\logic\ApiAssetLogic;
use util\Excel;
class ReviewsLogic extends BasicLogic
{

    /**
     * @desc   获取评论数据列表接口
     * @author luckyXiong
     * @date   2025-04-24
     */
    public function getList($params=[]){
        $limit         = getIsset($params,'limit',10);
        $title         = $params['title']??'';
        $spu           = $params['spu']??'';
        $review_id     = $params['review_id']??'';
        $date_created  = getIsset($params,'date_created');
        $create_time   = getIsset($params,'create_time');
        $where         = [];

        if($title){
            $where[]   =  ['title', 'like', '%' . $title . '%'];
        }


        if($spu){
            $where[]   =  ['spu', '=',$spu];
        }


        if($review_id){
            $where[]   =  ['review_id', '=',$review_id];
        }


        if (!empty($date_created)) {
            $where[]  = ['date_created', '>=', date('Y-m-d H:i:s',strtotime($date_created[0]))];
            $where[]  = ['date_created', '<=', date('Y-m-d H:i:s',strtotime($date_created[1]) + 3600*24-1)];
        }


        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        $field = '*';
        $list   = Db::name('customer_review_log')
            ->field($field)
            ->where($where)
            ->order('create_time desc')
            ->paginate($limit);
        $lists = $list->items()?:[];
        $operater_ids    = array_column($lists,'operate_id');
        //批量获取创建人;
        $admin_users     = Db::name('system_admin')->field('id,username')->whereIn('id',$operater_ids)->select()->toArray();
        $admin_users_map = array_column($admin_users,null,'id');
        foreach ($lists as $k=>$v) {
            $shopify_normal_imgs              = $v['shopify_normal_imgs'] ? json_decode($v['shopify_normal_imgs'],true):'';
            $lists[$k]['shopify_normal_imgs'] = $shopify_normal_imgs;
            $admin_users_info         = $admin_users_map[$v['operate_id']]??'';
            $lists[$k]['operater']   = $admin_users_info['username']??'';
        }

        $data = [
            'list'   => $lists,
            'total'  => $list->total(),
        ];
        return  $this->jsonMessage(200,true,'获取成功',$data);
    }






    /**
     * @desc   导入数据处理
     * @author luckyXiong
     * @date   2025-01-24
     */
    public function importInfo($params){
        try{
            $result = CommonSystemImportService::staticModel()->operate_import_data([
                    $this,//当前对应的service
                    'save',//类型: template 下载模板; save :保存 导入
                    CommonSystemImportService::TYPE_IMPORT_REVIEW_PAGE,
                    1,
                    $params
                ]
            );
        }catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }


    /**
     * @desc 将导入数据写入目标表
     * @author xx
     * @date 2024-03-21
     */
    public function import_order_review_page($params=[]){
        $key = 'import_order_review_page:'.time();
        $redis_lock = new RedissLock();
        $lock = $redis_lock::lock($key, $redis_lock::UNBLOCK, 500);
        $review_id       =   getIsset($params,'review_id');
        $user_name       =   getIsset($params,'user_name');
        $profile_url     =   getIsset($params,'profile_url');
        $rating          =   getIsset($params,'rating');
        $title           =   getIsset($params,'title');
        $review_url      =   getIsset($params,'review_url');
        $asin            =   getIsset($params,'asin');
        $content         =   getIsset($params,'content');
        $date            =   getIsset($params,'date');
        $format_strip    =   getIsset($params,'format_strip');
        $verified        =   getIsset($params,'verified');
        $helpful         =   getIsset($params,'helpful');
        $video_url       =   getIsset($params,'video_url');
        $video_cover_url =   getIsset($params,'video_cover_url');
        $imgs            =   getIsset($params,'imgs');
        $normal_imgs     =   getIsset($params,'normal_imgs');
        $spu             =   getIsset($params,'spu');

        $date_created        = $date        ? self::get_date($date) :'';
        $shopify_normal_imgs = $normal_imgs ? self::get_url($normal_imgs) :'';

        //数据入库逻辑
        $info = [
            'review_id'          =>$review_id,
            'user_name'          =>$user_name,
            'profile_url'        =>$profile_url,
            'rating'             =>$rating,
            'title'              =>$title,
            'review_url'         =>$review_url,
            'asin'               =>$asin,
            'country'            =>'us',
            'content'            =>$content,
            'date'               =>$date,
            'format_strip'       =>$format_strip,
            'verified'           =>$verified,
            'helpful'            =>$helpful,
            'video_url'          =>$video_url,
            'video_cover_url'    =>$video_cover_url,
            'imgs'               =>$imgs,
            'normal_imgs'        =>$normal_imgs,
            'shopify_normal_imgs'=>$shopify_normal_imgs,
            'date_created'       =>$date_created,
            'spu'                =>$spu ?:'',
            'operate_id'         => '96',
            'create_time'        =>date("Y-m-d H:i:s", time()),
        ];
        //update 2025-04-27
        $res = Db::name('customer_review_log')->insertGetId($info);
        $lock->unlock();
        $info['status'] = $res == 1 ? 1:2;
        return  $info;
    }


    /**
     * @param $row
     * @return string[]
     * @desc 数据title 导入组装数据结构
     */
    public function get_excel_row_data($row){

        $title   =  empty($row['F'])? '': trim($row['F']);

        $title   =  mb_convert_encoding($title, 'ASCII', 'UTF-8');
        $title   =  str_replace('?', '', $title);

        return [
            'review_id'         => empty($row['A'])? '': trim($row['A']),
            'avatar'            => empty($row['B'])? '': trim($row['B']),
            'user_name'         => empty($row['C'])? '': trim($row['C']),
            'profile_url'       => empty($row['D'])? '': trim($row['D']),
            'rating'            => empty($row['E'])? '': trim($row['E']),
            'title'             => $title,
            'review_url'        => empty($row['G'])? '': trim($row['G']),
            'asin'              => empty($row['H'])? '': trim($row['H']),
            'content'           => empty($row['I'])? '': trim($row['I']),
            'date'              => empty($row['J'])? '': trim($row['J']),
            'format_strip'      => empty($row['K'])? '': trim($row['K']),
            'verified'          => empty($row['L'])? '': trim($row['L']),
            'helpful'           => empty($row['M'])? '': trim($row['M']),
            'video_url'         => empty($row['N'])? '': trim($row['N']),
            'video_cover_url'   => empty($row['O'])? '': trim($row['O']),
            'imgs'              => empty($row['P'])? '': trim($row['P']),
            'normal_imgs'       => empty($row['Q'])? '': trim($row['Q']),
             'spu'              => empty($row['R'])? '': trim($row['R']),
        ];
    }


    private function get_date($dateString){
        preg_match("/on (\w+) (\d+), (\d+)/", $dateString, $matches);
        $month         = $matches[1];
        $day           = $matches[2];
        $year          = $matches[3];
        $monthNumber   = date("n", strtotime($month));
        $formattedDate = sprintf("%04d/%d/%d 00:00:00", $year, $monthNumber, $day);
        return  $formattedDate;
    }


    private function get_url($urls){
        $url_arr       = json_decode($urls,true);
        $arr           = [];
        if($url_arr && is_array($url_arr)){
              foreach($url_arr as $v){
                  $arr[] = self::test_url(['url'=>$v]);
              }
        }
        return  $arr ? json_encode($arr) : '';
    }


    /**
     * @desc   导入图片数据
     * @author luckyXiong
     * @date   2025-05-14
     */
    public function import_url($params=[]){
        $review_id   = $params['review_id']??'';
        $urls        = Db::name('customer_review_log')->where(['review_id'=>$review_id])->value('normal_imgs');
        $arr         = [];
        if($urls){
            $url_arr     = is_array($urls) ? $urls : json_decode($urls,true);
            foreach($url_arr as $v){
                $arr[] = self::test_url(['url'=>$v]);
            }
            $data  = $arr ? json_encode($arr) : '';

            Db::name('customer_review_log')->where(['review_id'=>$review_id])->update([
                'shopify_normal_imgs'=>$data
            ]);
        }
        return  $this->jsonMessage(200,true,'获取成功',$arr);
    }


    /**
     * @desc   导出接口
     * @author luckyXiong
     * @date   2025-04-24
     */
    public function export($params){
        $title         = $params['title']??'';
        $date_created  = getIsset($params,'date_created');
        $create_time   = getIsset($params,'create_time');
        $spu           = getIsset($params,'spu');
        $review_id     = $params['review_id']??'';
        $where         = [];

        if($title){
            $where[]   =  ['title', 'like', '%' . $title . '%'];
        }

        if (!empty($date_created)) {
            $where[]  = ['date_created', '>=', date('Y-m-d H:i:s',strtotime($date_created[0]))];
            $where[]  = ['date_created', '<=', date('Y-m-d H:i:s',strtotime($date_created[1]) + 3600*24-1)];
        }



        if($spu){
            $where[]   =  ['spu', '=',$spu];
        }


        if($review_id){
            $where[]   =  ['review_id', '=',$review_id];
        }


        if (!empty($create_time)) {
            $where[]  = ['create_time', '>=', date('Y-m-d H:i:s',strtotime($create_time[0]))];
            $where[]  = ['create_time', '<=', date('Y-m-d H:i:s',strtotime($create_time[1]) + 3600*24-1)];
        }

        $field = '*';
        $list   = Db::name('customer_review_log')
            ->field($field)
            ->where($where)
            ->select()
            ->toArray();

        $arr = [];
        $shopify_normal_imgs = '';
        try{
            foreach($list as $k=>$v){
                if($v['shopify_normal_imgs']){
                    $shopify_normal_imgs = json_decode($v['shopify_normal_imgs'],true);
                }
                $shopify_normal_imgs = $shopify_normal_imgs && is_array($shopify_normal_imgs) ? implode(',',$shopify_normal_imgs) : '';
                $arr[$k]['name'] = $v['user_name']??"";
                $arr[$k]['body'] = $v['content']??"";
                $arr[$k]['dateCreated'] = $v['date_created']??"";
                $arr[$k]['email'] = "";
                $arr[$k]['handle'] = "";
                $arr[$k]['productId'] ="";
                $arr[$k]['imageUrls'] = $shopify_normal_imgs;
                $arr[$k]['isApproved'] ="TRUE";
                $arr[$k]['rating'] = $v['rating']??"";
                $arr[$k]['reply']  = "";
                $arr[$k]['replyDateCreated'] = "";
                $arr[$k]['sku']             = "";
                $arr[$k]['title']           =  $v['title']??"";
                $arr[$k]['videoUrls']       =  $v['video_url']??"";
                $arr[$k]['isVerifiedBuyer'] =  "TRUE";
                $arr[$k]['variantId']       =  "";
                $arr[$k]['countryCode']     =  $v['country']??"";
            }
        }catch (\Exception $e) {
            echo  $e->getMessage();
            return error('添加失败:' . $e->getMessage());
        }


        $header   = [];
        $header[] = ['name', 'name'];
        $header[] = ['body', 'body'];
        $header[] = ['dateCreated', 'dateCreated'];
        $header[] = ['email', 'email'];
        $header[] = ['handle', 'handle'];
        $header[] = ['productId', 'productId'];
        $header[] = ['imageUrls', 'imageUrls'];
        $header[] = ['isApproved', 'isApproved'];
        $header[] = ['rating', 'rating'];
        $header[] = ['reply', 'reply'];
        $header[] = ['replyDateCreated', 'replyDateCreated'];
        $header[] = ['sku', 'sku'];
        $header[] = ['title', 'title'];
        $header[] = ['videoUrls', 'videoUrls'];
        $header[] = ['isVerifiedBuyer', 'isVerifiedBuyer'];
        $header[] = ['variantId', 'variantId'];
        $header[] = ['countryCode', 'countryCode'];
        $fileName = "order_views_detail".'_'.time();
        return Excel::exportData($arr, $header, $fileName, 'xlsx');
    }


    /**
     * @desc   删除spu
     * @author luckyXiong
     * @date   2025-05-14
     */
    public function deleteSpu($params){
           $ids = $params['ids']??'';
           if($ids){
               Db::name('customer_review_log')->whereIn('id',$ids)->delete();
           }
           return  $this->jsonMessage(200,true,'操作成功','');
    }



    /**
     * @desc   资产图片上传
     * @author luckyXiong
     * @date   2025-04-24
     */
    public function test_url($params){
        $link        = $params['url'] ??'';
        $shop_id     = 17;
        $theme_id = Db::name('shopify_themes')
            ->where('theme_id',177586798962)
            ->where('shop_id',$shop_id)
            ->order('id desc')
            ->value('theme_id');

        $shop_info      = Db::name('shops')->where('id',$shop_id)->find();
        $version        = Config('Logisticskey.shopify.api_versoin');
        $url            = $shop_info['myshopify_domain'].$version . "/themes/".$theme_id."/assets.json";
        $unique_key     = uniqid();
        $post = [
            'asset'=>[
                'key'     =>"assets/link".$unique_key.".png",
                'src'     =>$link,
                'theme_id'=>$theme_id,
            ]
        ];
        $return = HttpUtil::putUrl($url, $post, $shop_info);
        $return = json_decode($return, true);
        return $return['asset']['public_url'] ?? "";
    }




}